# Copyright 2010 Google Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Needed to avoid ambiguity in imports
from __future__ import absolute_import

import buzz
import oauth
import yaml

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import os.path
import logging

import web.helper
import models.tokens

OAUTH_CONFIG = yaml.load(open('oauth.yaml').read())

OAUTH_CONSUMER_KEY = OAUTH_CONFIG['oauth_consumer_key']
OAUTH_CONSUMER_SECRET = OAUTH_CONFIG['oauth_consumer_secret']

class StartHandler(webapp.RequestHandler):
  @property
  def client(self):
    if not hasattr(self, '_client') or not self._client:
      self._client = buzz.Client()
      self._client.build_oauth_consumer(
        OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET
      )
      self._client.oauth_scopes.append(buzz.READONLY_SCOPE)
    return self._client

  def get(self):
    cookies = web.helper.parse_cookies(self)
    if cookies:
      db_access_token = models.tokens.AccessToken.from_key(
        cookies.get('access_token')
      )
      if db_access_token:
        self.client.build_oauth_access_token(
          db_access_token.oauth_key,
          db_access_token.oauth_secret
        )

        posts = []
        for post in self.client.posts('@consumption'):
          if (len(posts) >= 20): 
            break
          posts.append(post)

        template_values = {
          'posts': posts,
        }
        path = os.path.join(
          os.path.dirname(__file__), '..', 'templates', 'start.html'
        )
        
        self.response.out.write(template.render(path, template_values))
      else:
        web.helper.clear_oauth_token_cookies(self)
        self.redirect('/oauth/init/')
    else:
      web.helper.clear_oauth_token_cookies(self)
      self.redirect('/oauth/init/')
